import {getMyData, getUserInfo, updateMemberField} from '../../api/member.js';
import Util from '../../utils/util.js';
import {CACHE_USERINFO} from "../../config";

let app = getApp();
Page({
  data: {
    showTipDialog: false,
    iosDialog1: false,
    dialogProfile: false,

    loading: false, // 是否加载中
    loadend: false, // 是否加载完毕
    loadTitle: '加载更多内容', // 提示语
    page: 1,
    lists: [],
    et_show: true,

    tabCurrent: 1,
    username: "",
    btnActive: true,

    nav2: [
      {title: "全部订单", icon: "all", status: -1},
      {title: "待付款", icon: "unpaid", status: 1},
      {title: "配送中", icon: "deliver", status: 2},
      {title: "售后", icon: "kefu", status: 3},
    ],

    nav1: [
      // {title: "优惠券", icon: "coupon", link: "/pages/coupon/index"},
      {title: "地址管理", icon: "address", link: "/pages/address/index"},
      {title: "联系客服", icon: "kefu"},
      {title: "账号管理", icon: "account", link: "/pages/member/profile"},
    ],

    nav3: [
      // {title: "商家入驻", icon: "shop", link: "/pages/supplier/form"},
      {title: "福利中心", icon: "gift", link: "/pages/shop/gift"},
      {title: "关于我们", icon: "about", link: "/pages/category/list?id=14"},
      {title: "我的反馈", icon: "question", link: "/pages/advice/list"},
      // {title: "中南餐厅", icon: "znct",},
    ],

    /*statusList: {
      1: "待付款",
      10: "进行中",
      11: "待接单",
      12: "出餐中",
      20: "已完成",

      21: "取餐中",
      22: "待配送",
      23: "配送中",
      24: "已送达",

      60: "已退款",
      80: "已取消",
    },*/
    field_key: ""

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    const that = this;
    this.setData({
      userInfo: app.globalData.userInfo || null,
    });

    wx.showLoading({
      title: "正在加载..."
    })
    Util.chekWxLogin().then(res => {
      wx.hideLoading()
      that.setData({userInfo: res.userInfo})

      if (Util.isEmpty(this.data.userInfo.avatar)) {
        this.setData({
          field_key: "avatar"
        })
      } else if (Util.isEmpty(this.data.userInfo.username)) {
        this.setData({
          field_key: "username"
        })
      }
    }).then((res) => {
      getMyData().then(res => {
        that.setData({...res.data})
      })
    }).catch(errmsg => {
      wx.hideLoading()
    })

  },

  onChooseAvatar(e) {
    const that = this;
    this.setData({
      avatarUrl: e.detail.avatarUrl
    })

    wx.uploadFile({
      url: app.globalData.url + '/api/file/upload',
      filePath: e.detail.avatarUrl,
      name: "fileData",
      formData: {
        'field_key': "avatar",
      },
      header: {
        token: wx.getStorageSync("cookie_token"),
        "Content-Type": "multipart/form-data"
      },
      success: function (res) {
        var data = res.data ? JSON.parse(res.data) : {};
        let userInfo = that.data.userInfo;
        userInfo.avatar = data.data.path;

        app.globalData.userInfo = userInfo;
        that.setData({
          userInfo: userInfo,
          field_key: ""
        })
        wx.setStorageSync(CACHE_USERINFO, JSON.stringify(userInfo));
        if (Util.isEmpty(userInfo.username)) {
          that.setData({
            field_key: "username"
          })
        }
      }
    })
  },

  inputDialogName(e) {  //input 输入
    let val = e.detail.value
    if (Util.isEmpty(val))
      return ""

    this.setData({
      username: val,
    })

  },

  updateUsername(e) { //更新昵称
    const that = this;
    if (Util.isEmpty(this.data.username))
      return app.Tips({title: "昵称必填", hideMask: true});

    let username = this.data.username;
    if (!this.data.btnActive)
      return;

    wx.showLoading({title: "正在更新..."})
    that.setData({
      btnActive: false
    })
    updateMemberField({
      field_key: "username",
      username: username
    }).then(res => {
      let userInfo = that.data.userInfo;
      userInfo.username = username;

      app.globalData.userInfo = userInfo;
      that.setData({
        userInfo: userInfo,
        field_key: ""
      })
      wx.setStorageSync(CACHE_USERINFO, JSON.stringify(userInfo));
    }).finally(() => {
      wx.hideLoading();
      that.setData({
        btnActive: true
      })
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  makePhoneCall(e) {
    const mobile = this.data.mobile || ''
    if (!mobile)
      return Util.Tips({title: '手机号码错误', hideMask: true});

    wx.makePhoneCall({
      phoneNumber: mobile,
      success: function () {
      },
      fail: function () {
      }
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    const that = this,
      is_refresh = wx.getStorageSync('is_refresh')

    if (is_refresh) {
      wx.removeStorageSync('is_refresh')
      this.loadUserInfo();
    }

  },

  goToOrder(e) {
    const key = e.currentTarget.dataset.key,
      navs = this.data.nav2;

    app.globalData.orderStatus = navs[key].status
    // wx.setStorageSync("orderStatus", app.globalData.orderStatus)
    wx.switchTab({
      url: '/pages/order/index'
    })
  },

  loadUserInfo() {
    let that = this;
    getUserInfo().then(res => {
      that.setData({
        member: res.data,
      });
    }).finally(() => {
      wx.stopPullDownRefresh();
    })
  },

  goPages(e) {
    const url = e.currentTarget.dataset.url,
      id = e.currentTarget.dataset.id,
      userInfo = this.data.userInfo;

    if (id == 'znct') {
      let supplier_id = 10002;
      if (!Util.isEmpty(userInfo) && !Util.isEmpty(userInfo.tags) && userInfo.tags.indexOf(2) !== -1) {
        supplier_id = 10001;
      }

      wx.navigateToMiniProgram({
        appId: 'wxf01be12354b159d2',
        path: 'pages/index/index?ssid=' + supplier_id,
        success(res) {
        },
        fail(res) {
        }
      })
      return true;
    }
    wx.navigateTo({
      url: url
    })
  },


  closeLayer(e) {
    this.setData({
      field_key: ""
    })
  },

  goConsole(e) {
    const that = this;
    const shop_token = wx.getStorageSync("shop_accessToken");
    if (Util.isEmpty(shop_token)) {
      return wx.redirectTo({
        url: '/pages/console/login'
      })
    }

    wx.redirectTo({
      url: '/pages/console/index'
    })
  },


  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.loadUserInfo();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  onLoadTabbar: function (e) {//底部tabbar返回数据
    const that = this;
    that.setData({
      bottom: parseInt(e.detail)
    })
    Util.checkIphone().then(res => {//检查是否是iphone x/11等
      that.setData({isIphoneX: res})
    })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})